#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open_tty(const char *port)
{
    struct termios termio;
    int fd, r;

    memset (&termio, 0, sizeof (termio));

    if ((fd = open (port, O_RDWR | O_NDELAY | O_NOCTTY)) == -1) {
        exit(-1);
    }

    fcntl(fd, F_SETFL, 0);
    r = tcgetattr(fd, &termio);

    /*
     *set the baud rate to 38400.
     */
    cfsetspeed(&termio, B38400);

    /*
     *set parity to none.
     */
    termio.c_cflag &= ~(PARENB | PARODD);

    /*
     *set databits to 8.
     */
    termio.c_cflag = ((termio.c_cflag & ~CSIZE) | CS8);

    /*
     *set flow control to none.
     */
    termio.c_cflag &= ~(CRTSCTS);
    termio.c_iflag &= ~(IXON | IXOFF | IXANY);
    termio.c_cflag |= (CLOCAL | CREAD);

    /*
     *apply our device config.
     */
    r = tcsetattr(fd, TCSANOW, &termio);

    if (r == -1) {
        exit(-1);
    }

    return fd;
}

int main(int argc, char** argv)
{   
    unsigned char cmd[16];
    unsigned char resp;
    int fd, count, checksum, n, i;
    struct termios options;

    memset(cmd, 0, sizeof(cmd));

    if(argc < 4 || argc > 16){
        printf("Usage: %s [port] [address] [command] [data] ...\n", argv[0]);
        return -1;
    }
    
    checksum = 0;
    cmd[0] = 58;
    for(i = 2; i < argc; i++){
        cmd[i] = atoi(argv[i]);
        checksum += cmd[i];
    }

    checksum = (256 - (58 + checksum)) % 256;
    cmd[argc] = checksum;

    fd = open_tty(argv[1]);

    printf("sending ...\n");

    printf("\ncmd = ");
    for(i = 0; i <= argc; i++){
        printf("%d ", cmd[i]);
    }
    printf("\n");

    count = write(fd, cmd, sizeof(cmd));
    printf("%d bites were written.\n", count);
   
    n = 0; 
    while(read(fd, &resp, sizeof(resp)) != -1){
        printf("resp[%d] = %d\n", n++, resp);
        //if(resp == 255){
          //exit(0);
        //}
    }

    close(fd);
	return 0;
}
